<?php
namespace app\api\controller;
use think\Controller;
use AliyunMNS\Exception\MessageNotExistException;
use AliyunMNS\Exception\MnsException;
use app\api\controller\Order;
use think\Db;


class Devicetool extends Controller{
    public function _initialize()
    {
        parent::_initialize();
        Vendor('iot.demo.Device#Util');
        Vendor('mns.AliyunMNS.Device#Client');
    }


    //测试获取队列消息
    public function mnstest($msgid = '15412285425bdd47')
    {   
        if (!empty($msgid)) {
            $msgId = $msgid;
        }
        
        $this->client = new \AliyunMNS\Client(config('endpoint'),config('accessid'),config('accesskey'));
        $queue = $this->client->getQueueRef('aliyun-iot-a1plNZn0KLj');//aliyun-iot-a1plNZn0KLj
        $flag = true;
        try{
            while ($flag) {
                if (cache($msgId)) {
                    $res = json_decode(cache($msgId));
                    // cache($msgId,null);
                    return apiResponse("200","结果获取成功！",$res);
                }
                $res = $queue->receiveMessage();
                if ($res -> isSucceed()) {
                    $resdata = json_decode($res->getMessageBody());
                    if (!empty($resdata -> payload)) {
                        $curdata = json_decode(base64_decode($resdata -> payload),true);
                        if (!empty($curdata['updateType'])) {
                            file_put_contents(ROOT_PATH."public/msglog/play.txt",date("Y-m-d H:i:s",time())."---------".base64_decode($resdata -> payload)."\n----------\n",FILE_APPEND);
                        }else{
                            file_put_contents(ROOT_PATH."public/msglog/msg.txt",date("Y-m-d H:i:s",time())."---------".base64_decode($resdata -> payload)."\n----------\n",FILE_APPEND);
                        }
                    }else{
                        continue;
                    }
                    
                    $receiptHandle = $res->getReceiptHandle();
                    
                    // file_put_contents('log/'.time().'.txt',json_encode($curdata));

                    if (!empty($curdata['updateType']) && $curdata['updateType'] == 'active_status') {
                        //处理订单状态更新
                        $order = new Order();
                        $order -> computeOrder($curdata['deviceId'],$curdata['data']);
                        $res2 = $queue->deleteMessage($receiptHandle);
                        $flag = false;
                    }else if(!empty($curdata['updateType']) && $curdata['updateType'] == 'passive status' && $curdata['data']['status'] == 'ready'){
                        $res2 = $queue->deleteMessage($receiptHandle);
                        $deviceData['device_status'] = 1;
                        $deviceData['update_time'] = time();
                        $deviceWhere['device_id'] = $curdata['deviceId'];
                        cache($curdata['data']['msgId'],json_encode($curdata),7*24*60*60);
                        Db::name('device')->where($deviceWhere)->update($deviceData);
                    }else if(!empty($curdata['status'])){
                        $res2 = $queue->deleteMessage($receiptHandle);
                        $deviceData['device_status'] = 1;
                        if ($curdata['status'] == 'offline') {
                            $deviceData['device_status'] = 3;
                        }
                        $deviceData['update_time'] = time();
                        $deviceWhere['device_id'] = $curdata['deviceName'];
                        Db::name('device')->where($deviceWhere)->update($deviceData);
                    }else{
                        $res2 = $queue->deleteMessage($receiptHandle);
                        if ( !empty($curdata['data']) && $curdata['data']['msgId'] && $msgId == $curdata['data']['msgId'] ) {
                            $flag = false;
                            cache($curdata['data']['msgId'],json_encode($curdata),7*24*60*60);
                            return apiResponse("200","结果获取成功！",$curdata);
                        }else if (!empty($curdata['data']) && $curdata['data']['msgId']) {
                            cache($curdata['data']['msgId'],json_encode($curdata),7*24*60*60);
                        }
                    }
                }else{
                    $flag = false;
                    return apiResponse("201","获取消息失败！");
                }
            }
        }catch (MessageNotExistException $e){
            return apiResponse("202","消息为空异常！");
        }
    }

    public function putStatus($deviceName = '865933031844968',$productKey = "a1plNZn0KLj")
    {

        $t = new \Util();
        $flag = true;
        while ($flag) {
            # code...
            $response = $t->queryDeviceByNameTest($productKey,$deviceName);
            if ( !$response->Success) {
                file_put_contents(ROOT_PATH."public/msglog/response.txt",date("Y-m-d H:i:s",time())."---------".json_encode($response)."\n----------\n",FILE_APPEND);
                return apiResponse("201","设备未注册!");
            }elseif ($response ->DeviceInfo ->DeviceStatus == 'OFFLINE') {
                sleep(1);
            }else{
                $flag = false;
                break;
            }
        }
        
        $msgId = substr(uniqid(mt_rand(), true), 0,10);
        $messageArray = [
            "getType" => "status",
            "time" => time()*1000,
            "data" => [
                "msgId" => $msgId
            ]
        ];
        $messageContent = json_encode($messageArray);
        $base64messageContent = base64_encode($messageContent);
        $response = $t->pubTest($productKey, $deviceName,$base64messageContent);
        if ($response->Success) {
            $resarr = [
                'requestId' => $response -> RequestId,
                'msgId' => $msgId
            ];
            return apiResponse("200","设备指令发送成功！",$resarr);
        }else{
            return apiResponse("201","指令发送失败！");
        }
        
    }

    // 测试注册设备
    public function registDevice($deviceName = '865933031844968',$productKey = "a1plNZn0KLj")
    {
        $t = new \Util();
        $response = $t->queryDeviceByNameTest($productKey,$deviceName);
        $response1 = $t->queryDeviceByNameTest($productKey,'n10_stm32');

        // file_put_contents('registDevice.txt',json_encode($response));
        // file_put_contents('registDevice1.txt',json_encode($response1));

        
        // dump($response);
        // exit();
        if (!$response1 -> Success || ($response1 -> Success && $response1 ->DeviceInfo -> DeviceStatus =="OFFLINE")) {
            $response1 -> Success = false;
            $response1 -> ErrorMessage = "鉴权设备不存在或未开启！";
            return $response1;
        }
        if ( !$response -> Success) {
            $response = $t->registDeviceTest($productKey,$deviceName);
            $deviceSecret = $response -> DeviceSecret;
            $msgId = substr(uniqid(mt_rand(), true), 0,10);
            $messageArray = [
                "deviceId" => $deviceName,
                "getType" => "authentication",
                "time" => time()*1000,
                "data" => [
                    "msgId" => $msgId,
                    "productId" => $productKey,
                    "deviceName" => $deviceName,
                    "deviceSecret" => $deviceSecret
                ]
            ];
            $messageContent = json_encode($messageArray);
            // echo $messageContent;
            $base64messageContent = base64_encode($messageContent);
            $response = $t->pubTest($productKey, 'n10_stm32',$base64messageContent);
            // echo $msgId;
        }else{
            $deviceSecret = $response -> DeviceInfo ->DeviceSecret;
            $msgId = substr(uniqid(mt_rand(), true), 0,10);
            $messageArray = [
                "deviceId" => $response -> DeviceInfo -> DeviceName,
                "getType" => "authentication",
                "time" => time()*1000,
                "data" => [
                    "msgId" => $msgId,
                    "productId" => $response -> DeviceInfo ->ProductKey,
                    "deviceName" => $response -> DeviceInfo -> DeviceName,
                    "deviceSecret" => $deviceSecret
                ]
            ];
            $messageContent = json_encode($messageArray);
            // echo $messageContent;
            $base64messageContent = base64_encode($messageContent);
            $response = $t->pubTest($productKey, $deviceName,$base64messageContent);
            // return apiResponse("201","设备已存在！");
            // echo $msgId;
        }
        $response -> msgId = $msgId;
        $response -> deviceId = $deviceName;
        $response -> deviceSecret = $deviceSecret;

        // dump($response);
        // exit();
        return $response;
    }


    public function test($productKey,$deviceName,$operate,$messageArray = ["getType" => "order","time" => 0,"data" => []])
    {
        $t = new \Util();
        // $productKey = $t->createProductTest();
        // $productKey = $this -> productKey;//a1feX5Krpl2
        // dump($productKey);
        // $t->updateProductTest($productKey);

        // dump($response);
        // $deviceName = $this -> deviceName;  //device
        // $deviceNames = $this -> deviceNameGenertor(1);

        // $response = $t->registDeviceTest($productKey,$deviceNames[0]);
        // $resp = $t->queryDeviceByNameTest($productKey,$deviceName);
        // if ($resp -> Success) {
        //     if ($resp -> DeviceInfo -> DeviceStatus == 'OFFLINE') {
        //         return apiResponse("205","设备当前处于下线状态！");
        //     }
        // }else{

        //     return apiResponse("201","设备状态不正常！",$resp);
        // }
        
        $flag = true;
        while ($flag) {
            # code...
            $resp = $t->queryDeviceByNameTest($productKey,$deviceName);
            if ( !$resp->Success) {
                file_put_contents(ROOT_PATH."public/msglog/response.txt",date("Y-m-d H:i:s",time())."---------".json_encode($resp)."\n----------\n",FILE_APPEND);
                return apiResponse("201","设备未注册!");
            }elseif ($resp ->DeviceInfo ->DeviceStatus == 'OFFLINE') {
                sleep(1);
            }else{
                $flag = false;
                break;
            }
        }
        
        // $t->queryDeviceTest($productKey);
        // $applyId = $t->applyDeviceWithNamesTest($productKey,$deviceNames);
        // sleep(2);
        // $t->queryApplyStatusTest($applyId);
        // $t->queryPageByApplyIdTest($applyId);
        // $response = $t->batchGetDeviceStatusTest($productKey,[$deviceName]);

        // $t->updateDeviceShadowTest($productKey,$deviceName);
        // $t->getDeviceShadowTest($productKey,$deviceName);
        // $operate = input("operate");
        
        $msgId = substr(uniqid(mt_rand(), true), 0,10);
        $messageArray["time"] = time()*1000;
        $messageArray["getType"] = $operate;
        $messageArray["data"]["msgId"] = $msgId;

        $messageContent = json_encode($messageArray);
        $base64messageContent = base64_encode($messageContent);
        $response = $t->pubTest($productKey, $deviceName,$base64messageContent);

        // dump($response);
        // $t->pubBroadcastTest($productKey);
        // $response = $t->rrpcTest($productKey, $deviceName,$base64messageContent);
        if ($response->Success) {
            $resarr = [
                'requestId' => $response -> RequestId,
                'msgId' => $msgId
            ];
            return apiResponse("200","设备指令发送成功！",$resarr);
        }else{
            return apiResponse("201","指令发送失败！");
        }
        
        // $t->saveDevicePropTest($productKey,$deviceName);
        // $t->queryDevicePropTest($productKey,$deviceName);
        // $t->deleteDevicePropTest($productKey,$deviceName);
    }


    /**
     * 我的测试用例
     * @author topqiang
     * @DateTime 2018-11-09T07:54:06+0800
     * @param    string                   $productKey [description]
     * @param    string                   $deviceName [description]
     * @return   [type]                               [description]
     */
    public function metest($productKey='a1plNZn0KLj',$deviceName='865933031844968')
    {
        $t = new \Util();
        // $productKey = $t->createProductTest();
        // $productKey = $this -> productKey;//a1feX5Krpl2
        // dump($productKey);
        // $t->updateProductTest($productKey);

        // dump($response);
        // $deviceName = $this -> deviceName;  //device
        // $deviceNames = $this -> deviceNameGenertor(1);

        // $response = $t->registDeviceTest($productKey,$deviceNames[0]);
        $resp = $t->queryDeviceByNameTest($productKey,$deviceName);
        if ($resp -> Success) {
            if ($resp -> DeviceInfo -> DeviceStatus == 'OFFLINE') {
                return apiResponse("201","设备当前处于下线状态！");
            }
        }else{
            return apiResponse("201","设备状态不正常！");
        }
        // $t->queryDeviceTest($productKey);
        // $applyId = $t->applyDeviceWithNamesTest($productKey,$deviceNames);
        // sleep(2);
        // $t->queryApplyStatusTest($applyId);
        // $t->queryPageByApplyIdTest($applyId);
        // $response = $t->batchGetDeviceStatusTest($productKey,[$deviceName]);

        // $t->updateDeviceShadowTest($productKey,$deviceName);
        // $t->getDeviceShadowTest($productKey,$deviceName);
        $operate = input("operate");
        $msgId = substr(uniqid(mt_rand(), true), 0,10);
        
        $messageArray = [
            "getType" => "order",
            "time" => time()*1000,
            "data" => [
                "msgId" => $msgId,
                "operate" => $operate,
                "option" => "normal"
            ]
        ];
        $messageContent = json_encode($messageArray);
        // file_put_contents('1.txt', $messageContent);
        $base64messageContent = base64_encode($messageContent);
        $response = $t->pubTest($productKey, $deviceName,$base64messageContent);
        // dump($response);
        // $t->pubBroadcastTest($productKey);
        // $response = $t->rrpcTest($productKey, $deviceName,$base64messageContent);
        dump($response);
        dump($messageArray);

         exit;
        if ($response->Success) {
            $resp = $this -> mnstest($msgId);
            dump( $response -> data );
            if (!$resp) {
                return apiResponse("201","队列消息未获取");
            }
        }else{
            return apiResponse("201","指令发送失败！");
        }
        $resarr = [
            'requestId' => $response -> RequestId,
            'deviceId' => $resp['deviceId'],
            'msgId' => $resp['data']['msgId'],
            'success' => $resp['data']['success']
        ];
        return apiResponse("201","设备执行指令成功！",$resarr);
        // $t->saveDevicePropTest($productKey,$deviceName);
        // $t->queryDevicePropTest($productKey,$deviceName);
        // $t->deleteDevicePropTest($productKey,$deviceName);
    }


    public function deviceNameGenertor($length)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $deviceNameArray = array();
        for ($i = 0; $i < $length; $i++)
        {
            $name = 'orange_';
            $l = 4;
            for ($j = 0; $j < $l; $j++)
            {
                $name .= $chars[mt_rand(0, strlen($chars) - 1)];
            }

            array_push($deviceNameArray,$name);
        }
        return $deviceNameArray;
    }
}
